from google.appengine.api.users import create_logout_url, create_login_url
from google.appengine.api import users


from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

from itertools import chain

from content.models import Article, Issue, Publication, Comment, Image
from people.models import Invite


def index(request):
	data = {}
	data['user'] = users.get_current_user()
	if data['user']:
		#FIXME: order the list using 'updated'
		#TODO: also get using invite permissions
		data['recent_pub'] = list(chain(Publication.all().filter('public =', True).filter('status =', True).order('-updated').fetch(5),
						Publication.all().filter('public =', False).filter('author =', data['user']).order('-updated').fetch(5)))
		#FIXME: order the list using 'updated'
		#TODO: also get using invite permissions
		data['recent_art'] = list(chain(Article.all().filter('public =', True).filter('status =', True).order('-updated').fetch(5), 
						Article.all().filter('public =', False).filter('author =', data['user']).order('-updated').fetch(5)))	
		data['l_url'] = create_logout_url(request.get_full_path())
	else:
		data['recent_pub'] = Publication.all().filter('public =', True).filter('status =', True).order('-updated').fetch(5)
		data['recent_art'] = Article.all().filter('public =', True).filter('status =', True).order('-updated').fetch(5)
		data['l_url'] = create_login_url(request.get_full_path())

	return render_to_response('home/index/index.html', data)

def dashboard(request):
	user = users.get_current_user()
	#TODO: search entrys using permission field (to check what entries 'user' has permission to change/collaborate)
	#TODO: paginates entries
	articles = Article.all().filter('author =', user)
	issues = Issue.all().filter('author =', user)
	publications = Publication.all().filter('author =', user)
	comments = Comment.all().filter('author =', user)
	images = Image.all().filter('author =', user)
	invites = Invite.all().filter('entry.author =', user)

	data = { 'articles': articles,
		'issues': issues,
		'publications': publications,
		'comments': comments, 
		'invites': invites, 
		'images': images, 
		}
	return render_to_response('home/dashboard/index.html', data)	
